<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use think\Db;
use think\Validate;
use cmf\controller\RestBaseController;

class PublicController extends RestBaseController
{
    // 用户注册
    public function register()
    {
    	//var_dump('111111111');die;
        $validate = new Validate([
            'phone'          => 'require',
            'password'          => 'require|length:8,16|alphaNum',
            'verification_code' => 'require'
        ]);

        $validate->message([
            'phone.require'          => '请输入手机号!',
            'password.require'          => '请输入您的密码!',
            'password.length'          => '密码请设置8~16个字符!',
            'password.alphaNum'          => '密码请设置字母加数字!',
            'verification_code.require' => '请输入数字验证码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $user = [];

        $userQuery = Db::name("app_user");
        //var_dump($userQuery);die;
        if (Validate::is($data['phone'], 'email')) {
            $user['user_email'] = $data['phone'];
            //$userQuery          = $userQuery->where('user_email', $data['username']);
        } else if (preg_match('/^1[345678]\d{9}$/', $data['phone'])) {
            $user['phone'] = $data['phone'];
            $userQuery      = $userQuery->where('phone', $data['phone']);
        } else {
            $this->error(['code'=>-100,'msg'=>'请输入正确的手机格式!']);
        }

        $errMsg = cmf_check_verification_code($data['phone'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error(['code'=>-101,'msg'=>$errMsg]);
        }

        $findUserCount = $userQuery->count();
        //var_dump($findUserCount);die;
        if ($findUserCount > 0) {
            $this->error(['code'=>-200,'msg'=>'此用户已存在!']);
        }

        $user['createTime'] = date('Y-m-d H:i:s');
        //$user['role'] = $data['role']?$data['role']:1;
       
        $user['password']   = sha1($data['password']);
        //var_dump($user);die;
        $result = $userQuery->insertGetId($user);
        if (empty($result)) {
            $this->error(['code'=>-300,'msg'=>"注册失败,请重试!"]);
        }
        //$findUser = $userQuery->where(['phone'=>$data['phone']])->find();
        $userTokenQuery = Db::name("user_token")
            ->where('user_id', $result)
            ->where('device_type', $data['device_type']);
        $findUserToken  = $userTokenQuery->find();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * 180;
        $token          = md5(uniqid()) . md5(uniqid());
        if (empty($findUserToken)) {
            $result = $userTokenQuery->insert([
                'token'       => $token,
                'user_id'     => $result,
                'expire_time' => $expireTime,
                'create_time' => $currentTime,
                'device_type' => $data['device_type']
            ]);
        } else {
            $result = $userTokenQuery
                ->where('user_id', $result)
                ->where('device_type', $data['device_type'])
                ->update([
                    'token'       => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }

        

        $this->success("注册成功!",['token' => $token]);

    }

    // 用户登录 TODO 增加最后登录信息记录,如 ip
    public function login()
    {
        $validate = new Validate([
            'phone' => 'require',
            'password' => 'require'
        ]);
        $validate->message([
            'phone.require' => '请输入手机号!',
            'password.require' => '请输入您的密码!'
        ]);

        $data = $this->request->param();
       
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userQuery = Db::name("app_user");
         if (preg_match('/^1[345678]\d{9}$/', $data['phone'])) {
            $userQuery = $userQuery->where('phone', $data['phone']);
        }else{
            $this->error(['code'=>-100,'msg'=>'请输入正确的手机格式!']);
        } 

        $findUser = $userQuery->find();

        if (empty($findUser)) {
            $this->error(['code'=>-200,'msg'=>'用户不存在!']);
        } else {

            if (sha1($data['password'])!= $findUser['password']) {
                $this->error(['code'=>-201,'msg'=>"密码不正确!"]);
            }
        }

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];

        if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
            $this->error(['code'=>-300,'msg'=>"请求错误,未知设备!"]);
        }

        $userTokenQuery = Db::name("user_token")
            ->where('user_id', $findUser['id'])
            ->where('device_type', $data['device_type']);
        $findUserToken  = $userTokenQuery->find();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * 180;
        $token          = md5(uniqid()) . md5(uniqid());
        if (empty($findUserToken)) {
            $result = $userTokenQuery->insert([
                'token'       => $token,
                'user_id'     => $findUser['id'],
                'expire_time' => $expireTime,
                'create_time' => $currentTime,
                'device_type' => $data['device_type']
            ]);
        } else {
            $result = $userTokenQuery
                ->where('user_id', $findUser['id'])
                ->where('device_type', $data['device_type'])
                ->update([
                    'token'       => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }


        if (empty($result)) {
            $this->error(['code'=>-300,'msg'=>"登录失败!"]);
        }
      
        
     
        
       
        $this->success("登录成功!", ['token' => $token]);
    }



    //验证码登录
    public function verify_login(){
    	$validate = new Validate([
            'phone' => 'require',
            'verification_code' => 'require'
        ]);
        $validate->message([
            'phone.require' => '请输入手机号!',
            'verification_code.require' => '请输入您的短信验证码!!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userQuery = Db::name("app_user");
         if (preg_match('/^1[345678]\d{9}$/', $data['phone'])) {
            $userQuery = $userQuery->where('phone', $data['phone']);
        } 

        $findUser = $userQuery->find();

        if (empty($findUser)) {
            $this->error(['code'=>-200,'msg'=>'用户不存在!']);
        } 

        $errMsg = cmf_check_verification_code($data['phone'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];

        if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
            $this->error(['code'=>-300,'msg'=>"请求错误,未知设备!"]);
        }



        $userTokenQuery = Db::name("user_token")
            ->where('user_id', $findUser['id'])
            ->where('device_type', $data['device_type']);
        $findUserToken  = $userTokenQuery->find();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * 180;
        $token          = md5(uniqid()) . md5(uniqid());
        if (empty($findUserToken)) {
            $result = $userTokenQuery->insert([
                'token'       => $token,
                'user_id'     => $findUser['id'],
                'expire_time' => $expireTime,
                'create_time' => $currentTime,
                'device_type' => $data['device_type']
            ]);
        } else {
            $result = $userTokenQuery
                ->where('user_id', $findUser['id'])
                ->where('device_type', $data['device_type'])
                ->update([
                    'token'       => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }


        if (empty($result)) {
            $this->error(['code'=>-300,'msg'=>"登录失败!"]);
        }

        $this->success("登录成功!", ['token' => $token]);
    }


    //校验登录
    public function check_login(){
    	if($this->getUserId()){
    		$this->success('校验成功',$this->getUserId());
    	}else{
    		$this->error('校验失败');
    	}
    }
	//检验登录统计使用次数
	public function login_check_login(){
		if($this->getUserId()){
			$id=$this->getUserId();
			db("app_user")->where(['id'=>$id])->setInc("use_num");
			db("app_user_log")->insert(['userId'=>$id,'createTime'=>date('Y-m-d H:i:s')]);
    		$this->success('校验成功',$this->getUserId());
    	}else{
    		$this->error('校验失败');
    	}	
	}

    // 用户退出
    public function logout()
    {
        $userId = $this->getUserId();
       
        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $userId,
            'device_type' => $this->deviceType
        ])->update(['token' => '']);

        $this->success("退出成功!");
    }

    // 用户密码重置
    public function passwordReset()
    {
        $validate = new Validate([
            'phone'          => 'require',
            'password'          => 'require',
            'verification_code' => 'require'
        ]);

        $validate->message([
            'phone.require'          => '请输入手机号!',
            'password.require'          => '请输入您的密码!',
            'verification_code.require' => '请输入数字验证码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userWhere = [];
        if (preg_match('/^1[345678]\d{9}$/', $data['phone'])) {
            $userWhere['phone'] = $data['phone'];
        } else {
            $this->error(['code'=>-100,'msg'=>'请输入正确的手机格式!']);
        }

        $errMsg = cmf_check_verification_code($data['phone'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error(['code'=>-101,'msg'=>$errMsg]);
        }

        $userPass = sha1($data['password']);
        Db::name("app_user")->where($userWhere)->update(['password' => $userPass]);

        $this->success("密码重置成功,请使用新密码登录!");

    }
}
